﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MD5Checksum
{
    public partial class UIForm : Form
    {
        public UIForm()
        {
            InitializeComponent();
        }

        private void btnBrowseInputFile_Click(object sender, EventArgs e)
        {
            DialogResult d = openFileDialog1.ShowDialog();
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            tbInputFile.Text = openFileDialog1.FileName;
        }

        private void btnGenerateMD5_Click(object sender, EventArgs e)
        {
            string[] extFilters = tbFileFilter.Text.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            int dateFilter = Convert.ToInt32(tbDateFilter.Text);
            string[] args = tbInputArgs.Text.Split(Environment.NewLine.ToCharArray());
            string dirStrip = tbDirStrip.Text;
            bool isRecursive = chkIsRecursive.Checked;
            bool isModifiedInclude = chkModifiedInclude.Checked;
            string result = GenerateMD5Checksum(isRecursive, isModifiedInclude, dateFilter, extFilters, ",", args);
            result = result.Replace(dirStrip, string.Empty);
            string outputFile = "md5checksum." + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
            File.WriteAllText(outputFile, result);
            MessageBox.Show(outputFile+ " created", "MD5 output");
        }

        private void btnCompare_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            string fileName = Path.GetFileName(tbInputFile.Text).Replace(".csv", "") + ".compared.csv";
            string[] lines = File.ReadAllLines(tbInputFile.Text);
            foreach (string line in lines)
            {
                bool isMatch = true;
                string[] arr = line.Split(",".ToCharArray());
                if (arr.Length != 2)
                {
                    continue;
                }
                string md5Str = arr[0];
                string file = tbDirAppend.Text + arr[1];
                string md5StrCurr = Helper.GetMd5HashFromFile(file);
                if (!md5Str.Equals(md5StrCurr))
                    isMatch = false;
                string newLine = line;
                if (!isMatch)
                {
                    FileInfo fInfo = new FileInfo(file);
                    string modifiedTime = fInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                    newLine += ",FALSE," + md5StrCurr + "," + modifiedTime;
                }
                sb.Append(newLine).Append(Environment.NewLine);
            }
            File.WriteAllText(fileName, sb.ToString());
            MessageBox.Show("Compare completed & saved to " + fileName, "MD5 checksum compare");
        }

        public string GenerateMD5Checksum(bool isRecursive, bool isModifiedInclude, int dateFilter, string[] extFilters, string delimited, params string[] args)
        {
            IList<string> files = Helper.GetAllFiles(isRecursive, dateFilter, args);
            StringBuilder sb = new StringBuilder();
            foreach (string file in files)
            {
                if (extFilters.Length > 0 && !Helper.IsContains(extFilters, Path.GetExtension(file)))
                    continue;
                string md5 = Helper.GetMd5HashFromFile(file);
                sb.Append(md5).Append(delimited).Append(file);
                if (isModifiedInclude)
                {
                    string formatDate = txtModifiedFormat.Text;
                    FileInfo f = new FileInfo(file);
                    string modifiedStr = string.Empty;
                    try
                    {
                        modifiedStr = f.LastWriteTime.ToString(formatDate);
                        sb.Append(delimited).Append(modifiedStr);
                    }
                    catch (Exception ex)
                    {
                        File.AppendAllText("MD5Checksum.log", DateTime.Now.ToString("yyyyMMddHHmmss") + ": " + ex.Message + Environment.NewLine);
                    }
                }
                sb.Append(Environment.NewLine);
            }
            return sb.ToString();
        }

    }
}
